package com.hxzy.shop.commodity.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.hxzy.shop.commodity.dto.req.RechargeReq;
import com.hxzy.shop.commodity.dto.resp.RechargeResp;
import com.hxzy.shop.commodity.mapper.MerchantPlugsMapper;
import com.hxzy.shop.commodity.mapper.MerchantPlugspaylogMapper;
import com.hxzy.shop.commodity.service.MerchantPlugsService;
import com.hxzy.shop.commodity.utils.MerchantThreadLocalUtils;
import com.hxzy.shop.entity.MerchantPlugs;
import com.hxzy.shop.entity.MerchantPlugspaylog;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 腾讯云saas订单 服务实现类
 * </p>
 *
 * @author qy
 * @since 2021-08-10
 */
@Service
public class MerchantPlugsServiceImpl extends ServiceImpl<MerchantPlugsMapper, MerchantPlugs> implements MerchantPlugsService {

    @Resource
    private MerchantPlugsMapper merchantPlugsMapper;

    @Resource
    private MerchantPlugspaylogMapper merchantPlugspaylogMapper;

    @Override
    public MerchantPlugs getPreInfo(Long plugId) {

        MerchantPlugs merchantPlugs = merchantPlugsMapper.selectOne(new LambdaQueryWrapper<MerchantPlugs>()
        .eq(MerchantPlugs::getPlugId,plugId));
        if (ObjectUtil.isEmpty(merchantPlugs)) {
            MerchantPlugs newMerchantPlugs = new MerchantPlugs();
            newMerchantPlugs.setPlugTotal(0);
            newMerchantPlugs.setPlugUsed(0);
            newMerchantPlugs.setPlugResidue(0);
            return newMerchantPlugs;
        }
        merchantPlugs.setId(null);

        return merchantPlugs;
    }

    @Override
    public String checkPayStatus(WxPayOrderNotifyResult notifyResult) {
        return null;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public RechargeResp recharge(RechargeReq rechargeReq) {
//        //插入购买记录表,用于生成订单id
//        MerchantPlugspaylog mpl = new MerchantPlugspaylog();
//        mpl.setPlugId(rechargeReq.getPlugId());
//        mpl.setPlugPrice(rechargeReq.getPlugPrice());
//        mpl.setPlugBuynum(rechargeReq.getNum());
//        mpl.setPayPrice(rechargeReq.getPlugPrice().multiply(new BigDecimal(rechargeReq.getNum().toString())));
//        mpl.setPayType(rechargeReq.getPayType());
//        mpl.setCreateTime(new Date());
//        //购买源都为1
//        mpl.setPluginSource(1);
//        merchantPlugspaylogMapper.insert(mpl);
//
//        //封装返回结果
//        MerchantPlugspaylog merchantPlugspaylog = merchantPlugspaylogMapper.selectById(mpl.getId());
//        RechargeResp rr = new RechargeResp();
//        rr.setMerchantId(merchantPlugspaylog.getMerchantId());
//        rr.setOrderNo(mpl.getId().toString());
//        rr.setPrice(mpl.getPayPrice());
//        return rr;
//    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public String checkPayStatus(WxPayOrderNotifyResult notifyResult) {
//        //获取返回的订单号
//        String outTradeNo = notifyResult.getOutTradeNo();
//        //获取附加信息：购买数量和商户id
//        String attach = notifyResult.getAttach();
//        Map<String, Object> parse = (Map<String, Object>) JSONObject.parse(attach);
//        Integer buyNum = (Integer) parse.get("buyNum");
//        Long merchantId = Long.valueOf(parse.get("merchantId").toString());
//        //远程调用不能传递merchantId过来，所以要将它存入线程，然后在MybatisPlus的配置中取出
//        MerchantThreadLocalUtils.setMerchantId(merchantId);
//        Long plugId = Long.valueOf(parse.get("plugId").toString());
//        if ("SUCCESS".equals(notifyResult.getResultCode())) {
//            //查询数据库改订单号是否存在
//            MerchantPlugspaylog one = null;
//            try {
//                one = merchantPlugspaylogMapper.selectById(Long.valueOf(outTradeNo));
//            } catch (NumberFormatException e) {
//                e.printStackTrace();
//                log.error("获取商户异常：" + e.getMessage());
//                return WxPayNotifyResponse.fail("失败");
//            }
//            if (ObjectUtil.isEmpty(one)) {
//                //订单不存在
//                return WxPayNotifyResponse.fail("失败");
//            }
//            if (!StringUtils.isBlank(one.getPayNum())) {
//                //说明已经产生了订单，不能进行下面的操作
//                return WxPayNotifyResponse.success("成功");
//            }
//            //获取总价格是否对应，微信传过来的是分，我们需要进行转化
//            Integer totalFee = notifyResult.getTotalFee();
//            BigDecimal total = new BigDecimal(totalFee);
//            //获取数据库总价
//            BigDecimal payPrice = one.getPayPrice();
//            Double v = payPrice.doubleValue() * 100;
//            Integer dbPrice = Integer.parseInt(String.valueOf(v.intValue()));
//            //向下取整
//            BigDecimal totalDb = new BigDecimal(dbPrice).setScale(2, BigDecimal.ROUND_HALF_DOWN);
//            BigDecimal totalWx = total.setScale(2, BigDecimal.ROUND_HALF_DOWN);
//            if (!totalDb.equals(totalWx)) {
//                //支付金额与数据库金额不对应
//                return WxPayNotifyResponse.fail("失败");
//            } else {
//                //处理业务逻辑
//                //处理商户插件表
//                MerchantPlugs merchantPlugs = merchantPlugsMapper.selectOne(new LambdaQueryWrapper<MerchantPlugs>()
//                        .eq(MerchantPlugs::getPlugId, plugId));
//                int i = 0;
//                Integer residueNum = 0;
//                if (ObjectUtil.isEmpty(merchantPlugs)) {
//                    //新增
//                    MerchantPlugs mp = new MerchantPlugs();
//                    mp.setPlugId(plugId);
//                    mp.setPlugTotal(buyNum);
//                    mp.setPlugUsed(0);
//                    mp.setPlugResidue(buyNum);
//                    mp.setCreateTime(new Date());
//                    mp.setMerchantId(merchantId);
//                    i = merchantPlugsMapper.insert(mp);
//                    residueNum = mp.getPlugResidue();
//                } else {
//                    //更新
//                    merchantPlugs.setPlugTotal(merchantPlugs.getPlugTotal() + buyNum);
//                    merchantPlugs.setPlugResidue(merchantPlugs.getPlugTotal() - merchantPlugs.getPlugUsed());
//                    i = merchantPlugsMapper.updateById(merchantPlugs);
//                    residueNum = merchantPlugs.getPlugResidue();
//                }
//                if (i <= 0) {
//                    return WxPayNotifyResponse.fail("失败");
//                }
//                //处理商户插件购买订单表
//                one.setPlugResidue(residueNum);
//                one.setPayNum(notifyResult.getTransactionId());
//                one.setCreateTime(new Date());
//                int j = merchantPlugspaylogMapper.updateById(one);
//                if (j <= 0) {
//                    return WxPayNotifyResponse.fail("失败");
//                }
//            }
//        }
//        return WxPayNotifyResponse.success("成功");
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RechargeResp recharge(RechargeReq rechargeReq) {
        //插入购买记录表,用于生成订单id
        MerchantPlugspaylog mpl = new MerchantPlugspaylog();
        mpl.setPlugId(rechargeReq.getPlugId());
        mpl.setPlugPrice(rechargeReq.getPlugPrice());
        mpl.setPlugBuynum(rechargeReq.getNum());
        mpl.setPayPrice(rechargeReq.getPlugPrice().multiply(new BigDecimal(rechargeReq.getNum().toString())));
        mpl.setPayType(rechargeReq.getPayType());
        mpl.setCreateTime(new Date());
        //购买源都为1
        mpl.setPluginSource(1);
        merchantPlugspaylogMapper.insert(mpl);

        //封装返回结果
        MerchantPlugspaylog merchantPlugspaylog = merchantPlugspaylogMapper.selectById(mpl.getId());
        RechargeResp rr = new RechargeResp();
        rr.setMerchantId(merchantPlugspaylog.getMerchantId());
        rr.setOrderNo(mpl.getId().toString());
        rr.setPrice(mpl.getPayPrice());
        return rr;
    }

}
